<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" :isSearchDisabled="isSearchDisabled" @reset="clearSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[188]">
        <el-form-item :label="$t('所属租户')" prop="adminUserId">
          <el-select style="width: 100%" @change="tenantChange" v-model="page.adminUserId" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="name">
          <el-input v-model="page.name" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证')" prop="idCard">
          <el-input v-model="page.idcard" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')" prop="loanRecordId">
          <el-input v-model="page.loanRecordId" clearable></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单状态')" prop="approvalResult">
          <el-select style="width: 100%" v-model="page.approvalResult" clearable>
            <el-option v-for="item in orderStatusList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[189]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('应还时间')" prop="shouldTime">
          <el-date-picker
              v-model="page.shouldTime"
              style="width: 100%"
              unlink-panels
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('还款时间')" prop="repaymentTime">
          <el-date-picker
              v-model="page.repaymentTime"
              style="width: 100%"
              type="daterange"
              value-format="yyyy-MM-dd"
              unlink-panels
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>


    <el-card shadow="never" style="margin-top: 10px">
      <!--      <el-row :gutter="24" style="margin: 0 0 10px 0;line-height: 32px;">-->
      <!--        <el-col v-show="$permiss[602]" :span="20">-->
      <!--          <el-link style="font-size: 18px;margin-right: 20px" type="primary" :underline="false">{{ $t('应还总金额') }} :-->
      <!--            {{ totalAmount.refundAmount }}-->
      <!--          </el-link>-->
      <!--          <el-link style="font-size: 18px;margin-right: 20px" type="primary" :underline="false">{{ $t('已还总金额') }} :-->
      <!--            {{ totalAmount.actualPayAmount }}-->
      <!--          </el-link>-->
      <!--          <el-link style="font-size: 18px;margin-right: 20px" type="primary" :underline="false">{{ $t('待还总金额') }} :-->
      <!--            {{ totalAmount.remainingAmount }}-->
      <!--          </el-link>-->
      <!--          <el-link style="font-size: 18px;margin-right: 20px" type="primary" :underline="false">{{ $t('减免总金额') }} :-->
      <!--            {{ totalAmount.remissionAmount }}-->
      <!--          </el-link>-->
      <!--        </el-col>-->
      <!--        <el-col :span="4" style="text-align: right" v-show="$permiss[781]">-->
      <!--          <el-button type="primary" @click="exportsExcel" :loading="exportsLoading">{{ $t('导出') }}</el-button>-->
      <!--        </el-col>-->
      <!--      </el-row>-->
      <Table :loading="tableLoading" max-height="600px" :table-column="tableColumn" :table-data="tableData" :page="page"
             @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange">
        <template slot="status" slot-scope="{row}">
          {{ row.status === 21 ? $t('成功') : row.status === 12 ? $t('失败') : '' }}
        </template>
        <template slot="handle" slot-scope="{row}">
          <!--              还款列表 操作栏按钮显示：-->
          <!--              1.订单为待还款状态时：-->
          <!--              1.1 正常还款期内（不含最后一天还款日）：线下还款、明细、-->
          <!--              1.2 最后一日还款日：线下还款、明细、展期-->
          <!--              2.订单为结清状态时：-->
          <!--              明细 -->
          <!--              3.订单为逾期状态时：-->
          <!--              线下还款、明细、减免、展期、逾期豁免-->
          <el-button type="text"
                     v-show="row.notRefundAmount !== 0 && $permiss[194] && row.approvalResult !== $t('结清')"
                     @click="tableRows('offline',row)">
            {{ $t('线下还款') }}
          </el-button>
          <el-button type="text" v-show="$permiss[196]" @click="tableRows('details',row)">{{ $t('明细') }}</el-button>
          <el-button type="text"
                     v-show="$permiss[192]  && row.approvalResult !== $t('结清') "
                     @click="tableRows('reduction',row)">
            {{ $t('减免') }}
          </el-button>
          <el-button type="text"
                     v-show="row.notRefundAmount !== 0 && $permiss[193]  && row.approvalResult !== $t('结清')"
                     @click="tableRows('exhibition',row)">{{ $t('展期') }}
          </el-button>
          <el-button type="text"
                     v-show="$permiss[522] && row.approvalResult === $t('逾期') "
                     @click="tableRows('late',row)">{{ $t('逾期豁免') }}
          </el-button>
        </template>
      </Table>
    </el-card>
    <!--    form表单弹窗 -->
    <Dialog :title="visible.title" :visible.sync="visible.isShow"
            @cancel="visible.isShow = false" @close="clearForm" @confirm="visibleConfirm" width="40%"
            :confirm-loading="dialogLoading">
      <component ref="visibleForm" :rows="tableRow" :is="dialogCompoents"
                 @loading="(val)=>{ dialogLoading = val }"></component>
    </Dialog>
    <!--    表格弹窗 -->
    <Dialog :title="$t('明细')" :visible.sync="visibleDetails" @close="clearDetailsForm" :footer="false"
            width="70%">
      <div>
        <el-button type="text">{{ $t('优惠券抵扣') }}</el-button>
        <Table border :page="false" max-height="400" :table-data="couponTableData" :table-column="couponTableColumn">
          <template slot="couponType" slot-scope="{row}">
            {{row.couponType === 1 ? $t('利息券') : row.couponType === 2 ? $t('还款券') : $t('罚息券')}}
          </template>
        </Table>
      </div>
      <div>
        <el-button type="text">{{ $t('还款详情') }}</el-button>
        <Table border :page="false" max-height="400" :table-data="repaymentTableData"
               :table-column="repaymentTableColumn">
        </Table>
      </div>
      <div style="margin-top: 10px">
        <el-button type="text">{{ $t('展期详情') }}</el-button>
        <Table border :page="false" max-height="400" :table-data="exhibitionTableData"
               :table-column="exhibitionTableColumn"></Table>
      </div>
    </Dialog>
  </div>
</template>

<script>
import {dateFormat, dateFormatSection, deepClone} from "@/utils/tools";
/*
/ 弹窗form组件
 */
// 线下还款
import offlineForm from "./compoents/offlineForm";
// 减免
import reductionForm from "./compoents/reductionForm";
// 展期
import exhibitionConfig from "./compoents/exhibitionForm";
// 逾期豁免
import lateExemption from './compoents/lateExemption'
import {export_json_to_excel} from "@/utils/exportExcel";
import {defaultTimeDate} from '@/utils/tools'
import {fetchRefundList, refundPageAmount, refundDetail, refundRollOverList, refundCouponDetails} from '@/api/finance'
import {selectProduct, selectTenant} from "@/api/system";

export default {
  name: 'repaymentList',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        shouldTime: defaultTimeDate(2)
      },
      tableLoading: false,
      tableData: [],
      tenantList: [],
      productList: [],
      orderStatusList: [
        {label: this.$t('待还款'), value: 6},
        {label: this.$t('逾期'), value: 8},
        {label: this.$t('结清'), value: 9},
      ],
      tableColumn: [
        {label: this.$t('订单编号'), fixed: "left", align: "center", prop: 'loanRecordId', width: 150},
        {label: this.$t('用户姓名'), prop: 'name', align: 'center', width: 100},
        {label: this.$t('手机号码'), prop: 'phone', align: 'center', width: 100},
        {label: this.$t("身份证"), prop: "idCard", align: "center", width: 100,},
        {label: this.$t('订单状态'), prop: 'approvalResult', align: 'center'},
        {label: this.$t('打款时间'), prop: 'paymentTime', align: 'center', width: 150},
        {label: this.$t('打款金额'), prop: 'laterAmount', align: 'center'},
        {label: this.$t('利息'), prop: 'interestAmount', align: 'center', width: 100},
        {label: this.$t('逾期罚息'), prop: 'overdueFine', align: 'center'},
        // {label: this.$t('剩余应还罚息'), prop: 'residueOverdueFine', align: 'center', width: 100},
        {label: this.$t('借款周期'), prop: 'loanTerm', align: 'center'},
        {label: this.$t('应还款时间'), prop: 'refundDate', align: 'center', width: 150},
        {label: this.$t('是否展期'), prop: 'isRollOver', align: 'center',},
        {label: this.$t('应还金额'), prop: 'refundAmount', align: 'center',},
        {label: this.$t('已还金额'), prop: 'actualPayAmount', align: 'center',},
        {label: this.$t('优惠券抵扣金额'), prop: 'deductionAmount', align: 'center', width: 150},
        {label: this.$t('减免金额'), prop: 'remissionAmount', align: 'center',},
        {label: this.$t('待还金额'), prop: 'notRefundAmount', align: 'center'},
        {label: this.$t('还款时间'), prop: 'refundTime', align: 'center', width: 150},
        {label: this.$t('还款类型'), prop: 'transferType', align: 'center', width: 100},
        {label: this.$t('还款渠道'), prop: 'refundChannelCode', align: 'center'},
        {label: this.$t('还款操作人'), prop: 'inputUserId', align: 'center', width: 100},
        {label: this.$t('APP名称'), prop: 'appName', align: 'center'},
        {label: this.$t('失败原因'), prop: 'failureReason', align: 'center', width: 150},
        {label: this.$t('所属租户'), align: "center", prop: 'adminUserName', isHide: !this.$permiss[188]},
        {
          label: this.$t('操作'),
          fixed: "right",
          align: "center",
          slot: 'handle',
          width: 250,
          isHide: !this.$permiss[719]
        }
      ],
      exportsLoading: false,
      visible: {
        isShow: false,
        type: '',
        title: ''
      },
      visibleDetails: false,
      dialogCompoents: null,
      tableRow: {},
      detailsForm: {
        repaymentTime: null
      },
      repaymentTableData: [],
      repaymentTableColumn: [
        {label: this.$t('还款流水'), prop: 'transferNumber', align: 'center',},
        {label: this.$t('还款时间'), prop: 'actualRefundTimestamp', align: 'center',},
        {label: this.$t('还款金额'), prop: 'actualRefundAmount', align: 'center',},
        {label: this.$t('操作人'), prop: 'inputUserId', align: 'center',},
        {label: this.$t('还款通道'), prop: 'channelCode', align: 'center',},
        {label: this.$t('备注'), prop: 'description', align: 'center',},
      ],
      exhibitionTableData: [],
      exhibitionTableColumn: [
        {label: this.$t('展期时间'), prop: 'overTime', align: 'center', minWidth: 150},
        {label: this.$t('展期金额'), prop: 'rollOverAmount', align: 'center',},
        {label: this.$t('原还款时间'), prop: 'originalRefundTime', align: 'center', minWidth: 150},
        {label: this.$t('展期天数'), prop: 'rollOverDay', align: 'center',},
        {label: this.$t('展期次数'), prop: 'rollOverNum', align: 'center',},
        {label: this.$t('展期后还款时间'), prop: 'nowRefundTime', align: 'center', minWidth: 150},
        {label: this.$t('展期利率'), prop: 'delayFee', align: 'center',},
        {label: this.$t('展期费用'), prop: 'delayAmount', align: 'center',},
      ],
      couponTableData: [],
      couponTableColumn: [
        {label: this.$t('优惠券名称'), prop: 'couponName', align: 'center',},
        {label: this.$t('优惠券类型'), prop: 'couponType', align: 'center', slot:'couponType',minWidth: 120},
        {label: this.$t('面额'), prop: 'amount', align: 'center',},
        {label: this.$t('实际抵扣金额'), prop: 'deductionAmount', align: 'center', minWidth: 120},
        {label: this.$t('核销时间'), prop: 'deductionTime', align: 'center', minWidth: 120},
      ],
      totalAmount: {},
      dialogLoading: false,
      isSearchDisabled: false
    }
  },

  mounted() {
    this.getTableData()
    this.getSelect()
  },
  methods: {
    async getTableData() {
      this.tableLoading = true
      this.isSearchDisabled = true
      const [shouldStart, shouldEnd] = dateFormatSection(this.page.shouldTime)
      const [refundStart, refundEnd] = dateFormatSection(this.page.repaymentTime)
      const params = {
        shouldStart,
        shouldEnd,
        refundStart,
        refundEnd,
        ...this.page
      }
      // 删除日期属性
      delete params.shouldTime
      delete params.repaymentTime
      // this.$permiss[602] && this.getTotalAmount(params)
      const res = await fetchRefundList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = (list || []).map(item => {
          const approvalResult = this.orderStatusList.find(val => val.value === item.approvalResult)
          item.transferType = item.transferType === 1 ? this.$t('线下') : item.transferType === 2 ? this.$t('线上') : ''
          item.isRollOver = item.rollOverDay === 0 ? this.$t('否') : this.$t('是')
          item.approvalResult = approvalResult ? approvalResult.label : ''
          return item
        })
        this.page.total = total
        this.tableLoading = false
        this.isSearchDisabled = false
      } else {
        this.tableLoading = false
        this.isSearchDisabled = false
      }
    },
    async getTotalAmount(params) {
      const res = await refundPageAmount(params)
      if (res.code === 1) {
        this.totalAmount = res.data || 0
      }
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page, 'productName', null)
      })
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    async getSelect() {
      selectProduct().then(res => {
        this.productList = res.data
      })
      selectTenant().then(res => {
        this.tenantList = res.data
      })
    },
    // 弹窗确认回调
    async visibleConfirm() {
      const code = await this.$refs.visibleForm.submitForm()
      if (code === 1) {
        this.clearForm()
        this.visible.isShow = false
        this.getTableData()
      }
    },
    // 清空搜索框
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.getTableData()
    },

    clearForm() {
      // 调用组件clearForm方法
      this.$refs.visibleForm.clearForm()
    },
    // 还款详情
    async getDetails() {
      const {loanRecordId} = this.tableRow
      const params = {
        loanRecordId,
      }
      const res = await refundDetail(params)
      if (res.code === 1) {
        this.repaymentTableData = res.data
      }
    },
    // 展期记录
    async getRollOverList() {
      const {loanRecordId} = this.tableRow
      const res = await refundRollOverList({
        loanRecordId,
      })
      if (res.code === 1) {
        this.exhibitionTableData = res.data
      }
    },
    // 优惠券使用明细
    async getCouponDetails() {
      const {loanRecordId} = this.tableRow
      const res = await refundCouponDetails({
        loanRecordId,
      })
      if (res.code === 1 && res.data) {
        this.couponTableData = [{...res.data}]
      }
    },
    disabledExhibition(date) {
      // 当前时间
      const nowDate = new Date()
      const value = date.substr(0, 10)
      if (value < dateFormat(nowDate, 'YYYY-mm-dd')) {
        return true
      } else if (value === dateFormat(nowDate, 'YYYY-mm-dd')) {
        return true
      } else {
        return false
      }
    },
    // 是否显示逾期豁免
    overdueInterval(row) {
      const {refundTime, refundDate} = row
      if (!refundTime) return false
      // 实际还款时间
      const loanTime = refundTime.substr(0, 10)
      //应还款时间
      const shouldTime = refundDate.substr(0, 10)
      return loanTime > shouldTime
    },
    // 详情重置
    clearDetailsForm() {
      this.exhibitionTableData = []
      this.repaymentTableData = []
      this.detailsForm = {
        repaymentTime: null
      }
      this.$refs.detailsForm.resetFields()
    },
    // 明细重置
    detailsReset() {
      this.detailsForm = {
        repaymentTime: null
      }
      this.$refs.detailsForm.resetFields()
      this.getDetails()
    },
    async tableRows(type, row) {
      this.tableRow = deepClone(row)
      if (type === 'details') {
        this.getDetails()
        this.getRollOverList()
        this.getCouponDetails()
        this.visibleDetails = true
      } else {
        let title = ''
        switch (type) {
          case 'offline' :
            title = this.$t('线下还款')
            this.dialogCompoents = 'OfflineForm'
            break;
          case 'exhibition' :
            title = this.$t('展期')
            this.dialogCompoents = 'exhibitionConfig'
            break;
          case 'reduction' :
            title = this.$t('减免')
            this.dialogCompoents = 'reductionForm'
            break;
          case 'late' :
            title = this.$t('逾期豁免')
            this.dialogCompoents = 'lateExemption'
        }
        this.visible = {
          isShow: true,
          title: title
        }
      }

    },
    // 导出excel
    async exportsExcel() {
      this.exportsLoading = true;
      const [shouldStart, shouldEnd] = dateFormatSection(this.page.shouldTime || [])
      const [refundStart, refundEnd] = dateFormatSection(this.page.repaymentTime || [])
      const params = {
        ...this.page,
        shouldStart, shouldEnd,
        refundStart, refundEnd
      };
      delete params.repaymentTime;
      delete params.shouldTime;
      const res = await this.$get("refundDtoExport", params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          item.transferType = item.transferType === 1 ? this.$t('线下') : item.transferType === 2 ? this.$t('线上') : ''
          item.isRollOver = item.rollOverDay === 0 ? this.$t('否') : this.$t('是')
          item.avoidAudit = item.avoidAudit === 1 ? this.$t('是') : item.avoidAudit === 2 ? this.$t('否') : ''
          item.approvalResult = this.orderStatusList.filter(val => val.value === item.approvalResult)[0].label
          return item
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("还款列表");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    },
  },
  components: {
    'OfflineForm': offlineForm,
    'ReductionForm': reductionForm,
    'ExhibitionConfig': exhibitionConfig,
    'LateExemption': lateExemption
  },
}
</script>

<style scoped>

</style>
